<?php

namespace Tbf\Bundle\PackageBundle\RelationPackage;

use Tbf\Bundle\PackageBundle\ActionInterface;
use Tbf\Bundle\TbfBundle\Controller\TbfController;

/**
 * 设置一个关系
 * 在第1个对象上面设置第2个对象的关系,顺序非常重要
 */
class SetAction extends TbfController implements ActionInterface
{
    /** @var RelationControllerConfig  */
    protected $config;
    public function setConfig(RelationControllerConfig $config)
    {
        $this->config = $config;
    }
    public function execute($input)
    {
        $err = $this->checkParameterExist($input,array($this->config->getIdName('first')));
        if ($err!==null) {
            return array(null,$err);
        }
        if (empty($input[$this->config->getIdListName('second')])) {
            $input[$this->config->getIdListName('second')] = array();
            $to_set_second = array();
        } elseif (!is_array($input[$this->config->getIdListName('second')])) {
            return array(null,'parameter '.$this->config->getIdListName('second').' is not array');
        } else {
            $to_set_second = $this->getDR($this->config->getEntityClassName('second'))
                ->findBy(array('id'=>$input[$this->config->getIdListName('second')]));
        }
        if (count($to_set_second)!==count($input[$this->config->getIdListName('second')])) {
            return array(null,'some '.$this->config->getIdListName('second').' not exist');
        }
        $first = $this->getDR($this->config->getEntityClassName('first'))->find($input[$this->config->getIdName('first')]);
        $set_second_list_function_name = $this->config->getSetAnotherListFunctionName('first');
        $first->{$set_second_list_function_name}($to_set_second);
        $this->getDM()->persist($first);
        $this->getDM()->flush();

        return array(null,null);
    }
}
